package 反射.cglib动态代理;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

interface UserService {
	public String getUserName();
}

class UserServiceImpl implements UserService {

	@Override
	public String getUserName() {
		System.out.println("UserServiceImpl getUserName");
		return null;
	}

}

class CglibProxy implements MethodInterceptor {
	private Log logger = LogFactory.getLog(CglibProxy.class);

	@Override
	public Object intercept(Object proxy, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
		logger.info("*********代理方法执行前************");
		Object retObj = methodProxy.invokeSuper(proxy, params);
		logger.info("*********代理方法执行后************");
		return retObj;
	}

	// 返回目标对象的代理对象
	public Object newProxy(Object target) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(target.getClass());
		enhancer.setCallback(this);
		enhancer.setClassLoader(target.getClass().getClassLoader());
		return enhancer.create();
	}
}

public class ProxyTestCglib {

	public static void main(String[] args) {
		// 创建目标对象
		UserService userService = new UserServiceImpl();
		CglibProxy proxy = new CglibProxy();
		// 创建代理对象
		UserService userService$Proxy = (UserService) proxy.newProxy(userService);
		userService$Proxy.getUserName();

	}
}
